import React,{Component} from "react";
import {Link, withRouter} from "react-router-dom";
import { Button, Checkbox, message} from "antd";
import moment from "moment";
import ajax from "../ajaxMethod";
import "../assets/stylesheets/unsubscribe.css"

//到这个页面必须传数据过来。
class Unsubscribe extends Component{
    constructor(props){
        super(props);
        this.state={
            ...this.props.location.values?(()=>{
                localStorage.setItem("valuesU", JSON.stringify(this.props.location.values));
                return this.props.location.values;
            })(): JSON.parse(localStorage.getItem("valuesU")),
            unsubVal:{//这个是这一页填上的值
                phone:"",
                goSelect: [],
                toSelect: [],
                goPassenger:[],
                toPassenger:[],
            }
        }
    }
    componentDidMount(){
        //根据订单号获取订单信息
        if(!this.state.data){//没有数据的话不能退票。
            this.props.history.push({
                pathname:"/"
            })
        }
        this.init();
    }
    //初始化选中的值
    init = () =>{
        let state = this.state, goSelect = [], toSelect = [], obj = {}, goPassenger = [], toPassenger = [];
        //passenger的
        for(let i = 0; i < state.data.goData.passenger.length; i++){
            goSelect.push(state.data.goData.passenger[i].IDnumber);
            switch(state.data.goData.passenger[i].type){
                case "0":{//成人
                    obj = {
                        IDnumber: state.data.goData.passenger[i].IDnumber,
                        pay: 1,
                        construction: 1,//机建
                        fuel: 1,//燃油
                        repent: 1//退票
                    };
                }break;
                case "1":{//儿童
                    obj = {
                        IDnumber: state.data.goData.passenger[i].IDnumber,
                        pay: 0.5,
                        construction: 0,//机建
                        fuel: 0.5,//燃油
                        repent: 1,
                    };
                }break;
                case "2":{//婴儿
                    obj = {
                        IDnumber: state.data.goData.passenger[i].IDnumber,
                        pay: 0.1,
                        construction: 0,//机建
                        fuel: 0,//燃油
                        repent: 1
                    };
                }break;
            }
            goPassenger.push(obj);
        }
        if(state.data.toID){//往返的
            for(let i = 0; i < state.data.toData.passenger.length; i++){
                toSelect.push(state.data.toData.passenger[i].IDnumber);
                switch(state.data.toData.passenger[i].type){
                    case "0":{//成人
                        obj = {
                            IDnumber: state.data.toData.passenger[i].IDnumber,
                            pay: 1,
                            construction: 1,//机建
                            fuel: 1,//燃油
                            repent: 1//退票
                        };
                    }break;
                    case "1":{//儿童
                        obj = {
                            IDnumber: state.data.toData.passenger[i].IDnumber,
                            pay: 0.5,
                            construction: 0,//机建
                            fuel: 0.5,//燃油
                            repent: 1//退票
                        };
                    }break;
                    case "2":{//婴儿
                        obj = {
                            IDnumber: state.data.toData.passenger[i].IDnumber,
                            pay: 0.1,
                            construction: 0,//机建
                            fuel: 0,//燃油
                            repent: 1//退票
                        };
                    }break;
                }
                toPassenger.push(obj);
            }
        }
        this.setState({unsubVal: {...this.state.unsubVal, goSelect: goSelect, toSelect: toSelect, goPassenger: goPassenger, toPassenger: toPassenger }});
    }
    onGoChange = (arr)=>{ 
        //计算有多少值
        let goPassenger = [], data = this.state.data.goData.passenger, obj = {}, index = 0;
        for(let i = 0; i < arr.length; i++){
            for(let j = 0; j < data.length; j++){
                if(data[j].IDnumber === arr[i]){
                    index = j;
                    break;
                }
            }
            switch(data[index].type){
                case "0":{//成人
                    obj = {
                        IDnumber: arr[i],
                        pay: 1,
                        construction: 1,//机建
                        fuel: 1,//燃油
                        repent: 1
                    };
                }break;
                case "1":{//儿童
                    obj = {
                        IDnumber: arr[i],
                        pay: 0.5,
                        construction: 0,//机建
                        fuel: 0.5,//燃油
                        repent: 1,
                    };
                }break;
                case "2":{//婴儿
                    obj = {
                        IDnumber: arr[i],
                        pay: 0.1,
                        construction: 0,//机建
                        fuel: 0,//燃油
                        repent: 1
                    };
                }break;
            }
            goPassenger.push(obj);
        }
        this.setState({unsubVal:{...this.state.unsubVal, goSelect: arr, goPassenger: goPassenger}}); 
    }
    onToChange = (arr) =>{ 
        let toPassenger = [], data = this.state.data.toData.passenger, obj = {}, index = 0;
        for(let i = 0; i < arr.length; i++){
            for(let j = 0; j < data.length; j++){
                if(data[j].IDnumber === arr[i]){
                    index = j;
                    break;
                }
            }
            switch(data[index].type){
                case "0":{//成人
                    obj = {
                        IDnumber: arr[i],
                        pay: 1,
                        construction: 1,//机建
                        fuel: 1,//燃油
                        repent: 1
                    };
                }break;
                case "1":{//儿童
                    obj = {
                        IDnumber: arr[i],
                        pay: 0.5,
                        construction: 0,//机建
                        fuel: 0.5,//燃油
                        repent: 1,
                    };
                }break;
                case "2":{//婴儿
                    obj = {
                        IDnumber: arr[i],
                        pay: 0.1,
                        construction: 0,//机建
                        fuel: 0,//燃油
                        repent: 1
                    };
                }break;
            }
            toPassenger.push(obj);
        }
        this.setState({unsubVal:{...this.state.unsubVal, toSelect: arr, toPassenger: toPassenger}}); 
    }
    changePhone = (e) =>{ this.setState({unsubVal:{...this.state.unsubVal, phone: e.target.value}}); }
    submit = (e) =>{
        let phoneExp = /^1[34578]\d{9}$/,
             _this = this;

        if(!phoneExp.test(this.state.unsubVal.phone)){//校验表单，只有手机号
            message.error("请输入正确格式的手机号");
        }else{
            //有返程的时候再发一个请求，一个一个请求的发
            let govalues = {
                username: _this.state.data.goData.username,
                orderID: _this.state.data.goData._id,
                flightID: _this.state.initalValues.goTrip.id,
                classType:_this.state.initalValues.goType,
                select: _this.state.unsubVal.goSelect,
                number: _this.state.data.goData.number
            };
            if(this.state.data.toID){
                ajax.postAjax("/interface/cancelOrder", govalues, res=>{
                    if(res.success){
                        ajax.postAjax("/interface/cancelOrder", {//返程
                            username: _this.state.data.toData.username,
                            orderID: _this.state.data.toData._id,
                            flightID: _this.state.initalValues.toTrip.id,
                            classType: _this.state.initalValues.toType,
                            select: _this.state.unsubVal.toSelect,
                            number: _this.state.data.toData.number//这个订单的总人数
                        }, res=>{
                            if(res.success){
                                console.log(res);
                                message.success("退票成功");
                                _this.props.history.replace({
                                    pathname:"/"
                                })
                            }else{
                                console.error(res.description);
                                message.error(res.description);
                            }
                        },err=>{
                            console.error(err);
                        })
                    }else{
                        console.error(res.description);
                        message.error(res.description);
                    }
                },err=>{
                    console.error(err);
                })
            }else{//单程
                ajax.postAjax("/interface/cancelOrder", govalues, res=>{
                    if(res.success){
                        console.log(res);
                        message.success("退票成功");
                        _this.props.history.replace({
                            pathname:"/"
                        })
                    }else{
                        console.error(res.description);
                        message.error(res.description);
                    }
                },err=>{
                    console.error(err);
                })
            }
        }
    }

    render(){
        console.log("退订的state----", this.state, this.props);
        const state = this.state;
        const initalValues = state.initalValues;
        const unsubVal = state.unsubVal;
        let goOptions =  [], 
            toOptions = [], 
            goDefault = [], 
            toDefault = [], 
            goClass = 'economyClass', 
            toClass = 'economyClass',
            goSum = {
                pay: 0,
                construction: 0,
                fuel: 0,
                repent: 0
            },
            toSum = {
                pay: 0,
                construction: 0,
                fuel: 0,
                repent: 0
            },
            sumPay = 0,
            sumRepent = 0;
        if(state.data.toID){//往返的
            for(let i = 0; i < state.data.goData.passenger.length; i++){
                goOptions.push({
                    label: state.data.goData.passenger[i].name,
                    value: state.data.goData.passenger[i].IDnumber
                });
                goDefault.push(state.data.goData.passenger[i].IDnumber);
            }
            for(let i = 0; i < state.data.toData.passenger.length; i++){
                toOptions.push({
                    label: state.data.toData.passenger[i].name,
                    value: state.data.toData.passenger[i].IDnumber
                });
                toDefault.push(state.data.toData.passenger[i].IDnumber);
            }
        }else{
            for(let i = 0; i < state.data.goData.passenger.length; i++){
                goOptions.push({
                    label: state.data.goData.passenger[i].name,
                    value: state.data.goData.passenger[i].IDnumber
                });
                goDefault.push(state.data.goData.passenger[i].IDnumber);
            }
        }
        switch(state.data.goData.classType){
            case 0: goClass = "economyClass";break;
            case 1: goClass = "businessClass";break;
            case 2: goClass = "firstClass"; break;
        }
        for(let i = 0; i < unsubVal.goPassenger.length; i++){
            goSum.pay += unsubVal.goPassenger[i].pay;
            goSum.construction += unsubVal.goPassenger[i].construction;
            goSum.fuel += unsubVal.goPassenger[i].fuel;
            goSum.repent += unsubVal.goPassenger[i].repent;
        }
        if(state.data.toID){
            switch(state.data.toData.classType){
                case 0: toClass = "economyClass";break;
                case 1: toClass = "businessClass";break;
                case 2: toClass = "firstClass"; break;
            }
            for(let i = 0; i <  unsubVal.toPassenger.length; i++){
                toSum.pay +=  unsubVal.toPassenger[i].pay;
                toSum.construction +=  unsubVal.toPassenger[i].construction;
                toSum.fuel +=  unsubVal.toPassenger[i].fuel;
                toSum.repent += unsubVal.toPassenger[i].repent;
            }
        }
        sumRepent = state.data.toID? 
            initalValues.toTrip[toClass].repent * toSum.repent + initalValues.goTrip[goClass].repent * goSum.repent:
            initalValues.goTrip[goClass].repent * goSum.repent;
        sumPay = (()=>{
            let sum = 0;
            sum += initalValues.goTrip[goClass].afterPrice * goSum.pay +
            initalValues.goTrip[goClass].construction * goSum.construction +
            initalValues.goTrip[goClass].fuel * goSum.fuel;
            if(state.data.toID){
                sum += initalValues.toTrip[toClass].afterPrice * toSum.pay +
                initalValues.toTrip[toClass].construction * toSum.construction +
                initalValues.toTrip[toClass].fuel * toSum.fuel;
            }
            return sum;
        })();
        
        return (
        <div id="unsubscribe">
            <div className="top">
                <div>
                    <div><Link to="/"><i className="logo"></i></Link></div>
                </div>
            </div>
            <div className="content">
                <div className="left">
                     <div className="tips">
                        <p><i>i</i><span>航程不收取任何退改费用，具体费用按产品提供方规定收取</span></p>
                    </div>
                    <div className="order-inf">
                        <h2>选择退订产品</h2>
                        {
                            state.data.toID?<div>
                                <div>
                                    <p className="trivle">去程：<span>{moment(state.data.goData.start.time).format("MM-DD")}</span>{state.data.goData.start.city}-{state.data.goData.end.city}</p>
                                    <Checkbox.Group options={goOptions} defaultValue={goDefault} onChange={this.onGoChange} />
                                </div>
                                <div>
                                    <p className="trivle">返程：<span>{moment(state.data.toData.start.time).format("MM-DD")}</span>{state.data.toData.start.city}-{state.data.toData.end.city}</p>
                                    <Checkbox.Group options={toOptions} defaultValue={toDefault} onChange={this.onToChange} />
                                </div>
                            </div>:
                            <div>
                                <div>
                                    <p className="trivle">行程：<span>{moment(state.data.goData.start.time).format("MM-DD")}</span>{state.data.goData.start.city}-{state.data.goData.end.city}</p>
                                    <Checkbox.Group options={goOptions} defaultValue={goDefault} onChange={this.onGoChange} />
                                </div>
                            </div>
                        }
                    </div>
                    <div className="contact">
                        <h2>确认联系方式</h2>
                        <div>
                            <input placeholder="请输入手机号" onChange={this.changePhone}></input>
                        </div>
                    </div>
                    <div className="reimburse">
                        <h2>报销</h2>
                        <div>
                            <Checkbox>需要报销退票凭证</Checkbox>
                        </div>
                    </div>
                    <Button onClick={this.submit}>提交退票</Button>
                </div>
                <div className="right">
                    <div className="title">
                        <h2>确认退款金额</h2>
                    </div>
                    <div className="product">
                        <p>退订产品 <i>￥</i><span>{sumPay}</span></p>
                        <div className="go-trip all-trip">
                            {state.data.toID?<p>去</p>:[]}
                            <div>
                                <span className="before">机票价</span>
                                <span className="price"><i>￥</i>{initalValues.goTrip[goClass].afterPrice}<span>x{goSum.pay}</span></span>
                            </div>
                            <div>
                                <span className="before">机建</span>
                                <span className="price"><i>￥</i>{initalValues.goTrip[goClass].construction}<span>x{goSum.construction}</span></span>
                            </div>
                            <div>
                                <span className="before">燃油</span>
                                <span className="price"><i>￥</i>{initalValues.goTrip[goClass].fuel}<span>x{goSum.fuel}</span></span>
                            </div>
                        </div>
                        {
                            state.data.toID?(()=>{
                                // 返回的路程
                                return <div div className="to-trip all-trip">
                                    <p>返</p>
                                    <div>
                                <span className="before">机票价</span>
                                <span className="price"><i>￥</i>{initalValues.toTrip[toClass].afterPrice}<span>x{toSum.pay}</span></span>
                            </div>
                            <div>
                                <span className="before">机建</span>
                                <span className="price"><i>￥</i>{initalValues.toTrip[toClass].construction}<span>x{toSum.construction}</span></span>
                            </div>
                            <div>
                                <span className="before">燃油</span>
                                <span className="price"><i>￥</i>{initalValues.toTrip[toClass].fuel}<span>x{toSum.fuel}</span></span>
                            </div>
                                </div>
                            })():[]
                        }
                    </div>
                    <div className="deduction">
                        <p>需扣款项<i>￥</i> <span>{sumRepent}</span> </p>
                        <div className="go-trip all-trip">
                            {state.data.toID?<p>去</p>:[]}
                            <div>
                                <span className="before">退票费</span>
                                <span className="price"><i>￥</i>{initalValues.goTrip[goClass].repent}<span>x{goSum.repent}</span></span>
                            </div>
                        </div>
                        {
                            state.data.toID?(()=>{
                                // 返回的路程
                                return <div div className="to-trip all-trip">
                                    <p>返</p>
                                    <div>
                                        <span className="before">退票费</span>
                                        <span className="price"><i>￥</i>{initalValues.toTrip[toClass].repent}<span>x{toSum.repent}</span></span>
                                    </div>
                                </div>
                            })():[]
                        }
                    </div>
                    <div className="refund">
                        <div>
                            <p className="before">实退金额:</p>
                            <p className="price after"><i>￥</i>{sumPay - sumRepent}</p>
                        </div>
                        <div>
                            <p className="before">退款方式:</p>
                            <p className="after">原路退回</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>)
    }
}

export default withRouter(Unsubscribe);